import express, { Request, Response } from "express"
import { LoggedInRequest } from "../../types"
import { checkError } from "../../utils/token"
import { CollectCtx } from "../../context/CollectCtx"
import { useCheckAndResponse } from "../../utils/common"

const mineRouter = express.Router()

mineRouter.get('/collect', async (req: LoggedInRequest, res: Response) => {
  try {

    const data = await CollectCtx.getInstance().collect({}, req.userInfo.userId)
    res.send({
      code: 1,
      msg: '查询成功',
      data: data
    })

  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

mineRouter.post('/collect', async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as { teaId: number }
    
    const data = await CollectCtx.getInstance().collect({ teaId: params.teaId }, req.userInfo.userId)

    if (data.length) {
      return res.send({
        code: 0,
        msg:"已收藏，请勿重复收藏"
      })
    }
    
    const result = await CollectCtx.getInstance().addCollect(params, req.userInfo.userId)

    useCheckAndResponse(res, result[0], '收藏成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

mineRouter.delete('/collect', async (req: LoggedInRequest, res: Response) => {
  try {
    const query = req.query as any as { collectId: number }
    
    const data = await CollectCtx.getInstance().collect({ collectId: query.collectId }, req.userInfo.userId)

    if (!data.length) {
      return res.send({
        code: 0,
        msg:"商品未收藏，不可取消"
      })
    }
    
    const result = await CollectCtx.getInstance().delCollect(data[0].collectId, req.userInfo.userId)

    useCheckAndResponse(res, result[0], '收藏已取消')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

mineRouter.get('/collect/judge', async (req: LoggedInRequest, res: Response) => {
  try {
    const query = req.query as any as {teaId: number}
    
    const data = await CollectCtx.getInstance().collect({teaId: query.teaId}, req.userInfo.userId)
    res.send({
      code: 1,
      msg: '查询成功',
      data: !!data.length
    })

  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

export default mineRouter